import React from 'react';
import {connect} from 'dva';
import styles from './Votemodify.css';
import MainLayout from '../components/layouts/MainLayout';
import {
  Form,
  Card,
  Button,
  Input,
  Switch,
  DatePicker,
  TimePicker,
  Select,
  InputNumber,
  Row,
  Col,
  Spin,
  message
} from 'antd';
import {routerRedux} from 'dva/router';
import moment from 'moment';


const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class VoteModifyForm extends React.Component {


  handleSubmit = (e) => {
    const submitVote = this.props.submitVote;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values);
        submitVote({...values, ...{id: this.props.vote.id}});
      }
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;

    if (this.props.vote.loading) {
      return (
        <Spin>
          <Card title="编辑投票"/>
        </Spin>
      );
    }

    var subjectItem;

    if (!this.props.subjects.loading) {
      const options = this.props.subjects.list.map((subject) => {
        return (
          <Option value={'' + subject.id} key={subject.id}>{subject.title}</Option>
        );
      });

      subjectItem = (
        <FormItem label="投票主题" hasFeedback>
          {getFieldDecorator('subject', {
            rules: [
              {required: true, message: '必须选择投票主题'}
            ],
            initialValue: '' + this.props.vote.subject.id
          })(
            <Select
              showSearch
              placeholder="选择投票主题"
              optionFilterProp="children"
              filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {options}
            </Select>
          )}
        </FormItem>
      );
    } else {
      subjectItem = (
        <Spin>
          <FormItem label="投票主题" hasFeedback>
            {getFieldDecorator('subject', {
              rules: [
                {required: true, message: '必须选择投票主题'}
              ]
            })(
              <Select
                showSearch
                style={{width: 200}}
                placeholder="选择投票主题"
                optionFilterProp="children"
                filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              >
              </Select>
            )}
          </FormItem>
        </Spin>
      );
    }

    var candidateItem;

    if (this.props.candidates.loading) {
      candidateItem = (
        <Spin>
          <FormItem label="候选对象" hasFeedback>
            {getFieldDecorator('candidate', {
              rules: [
                {required: true, message: '必须选择候选对象'}
              ]
            })(
              <Select
                mode="multiple"
                style={{width: '100%'}}
                placeholder="选择候选对象"
              >
              </Select>
            )}
          </FormItem>
        </Spin>
      );
    } else {
      const options = this.props.candidates.list.map((candidate) => {
        return (
          <Option value={'' + candidate.id} key={candidate.id}>{candidate.name}</Option>
        );
      });

      candidateItem = (
        <FormItem label="候选对象" hasFeedback>
          {getFieldDecorator('candidate', {
            rules: [
              {required: true, message: '必须选择候选对象'}
            ],
            initialValue: this.props.vote.candidates.map((candidate) => {
              return '' + candidate.id;
            })
          })(
            <Select
              mode="multiple"
              style={{width: '100%'}}
              placeholder="选择候选对象"
            >
              {options}
            </Select>
          )}
        </FormItem>
      );
    }

    const otherItems = (
      <div>
        <FormItem label="自定义标签" hasFeedback>
          {getFieldDecorator('tag', {
            rules: [],
          })(
            <Select
              mode="tags"
              style={{width: '100%'}}
            >
            </Select>
          )}
        </FormItem>

        <FormItem label="可以选择的选项个数，0表示不限制" hasFeedback>
          {getFieldDecorator('rule', {
            rules: [
              {required: true, message: '必须填写选项个数'}
            ],
            initialValue: this.props.vote.rule
          })(
            <InputNumber min={0}/>
          )}
        </FormItem>

        <FormItem label="是否要求登录投票" hasFeedback>
          {getFieldDecorator('permission', {
            rules: [
              {required: true, message: '必选选择是否要求登录投票'}
            ],
            initialValue: this.props.vote.permission == 1
          })(
            <Switch checkedChildren={'是'} unCheckedChildren={'否'}/>
          )}
        </FormItem>

        <FormItem label="投票时间间隔" hasFeedback>
          {getFieldDecorator('frequency', {
            rules: [
              {required: true, message: '必须选择投票时间间隔'}
            ],
            initialValue: this.props.vote.frequency
          })(
            <InputNumber min={0}/>
          )}
        </FormItem>

        <FormItem label="结果是否可见" hasFeedback>
          {getFieldDecorator('result_visibility', {
            rules: [
              {required: true, message: '必须选择结果是否可见'}
            ],
            initialValue: this.props.vote.result_visibility
          })(
            <Switch checkedChildren={'是'} unCheckedChildren={'否'}/>
          )}
        </FormItem>

        <FormItem label="展示模版" hasFeedback>
          {getFieldDecorator('template', {
            rules: [
              {required: true, message: '必须选择展示模版'}
            ],
            initialValue: this.props.vote.template
          })(
            <Select
              showSearch
              placeholder="选择模版"
              optionFilterProp="children"
              filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              <Option value="default">default</Option>
            </Select>
          )}
        </FormItem>

        <FormItem label="开始-结束时间" hasFeedback>
          {getFieldDecorator('start_end_time', {
            rules: [
              {required: true, message: '必须选择投票开始结束时间'}
            ],
            initialValue: [
              moment(this.props.vote.start_time, 'YYYY-MM-DD HH:mm:ss'),
              moment(this.props.vote.end_time, 'YYYY-MM-DD HH:mm:ss')
            ]
          })(
            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
          )}
        </FormItem>

      </div>
    );

    return (
      <Form onSubmit={this.handleSubmit} className={styles.normal}>
        {subjectItem}
        {candidateItem}
        {otherItems}
        <FormItem>
          <Button type="primary" htmlType="submit">发布投票</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedVoteModifyForm = Form.create()(VoteModifyForm);

const Votemodify = ({dispatch, subjects, candidates, vote}) => {

  function submitVote(query) {
    console.log(query);
    dispatch({
      type: 'vote/modify',
      payload: query
    });

    if (vote.error == '') {
      message.info('保存成功');
      dispatch(routerRedux.push({
        pathname: '/votes',
        query: {}
      }));
    } else {
      message.error(vote.error);
    }
  }

  return (
    <MainLayout>
      <Row>
        <Col span={3}>

        </Col>
        <Col span={18}>
          <Card title="编辑投票">
            <WrappedVoteModifyForm subjects={subjects} candidates={candidates} vote={vote}
                                   submitVote={submitVote}/>
          </Card>
        </Col>
        <Col span={3}>

        </Col>
      </Row>

    </MainLayout>
  );
}

function mapStateToProps({subjects, candidates, vote}) {
  return {
    subjects: subjects,
    candidates: candidates,
    vote: vote
  };
}

export default connect(mapStateToProps)(Votemodify);
